import { Form, Input, Toast } from 'antd-mobile'
import NavBarAgain from '../components/NavBarAgain'
import './Login.scss'
import { useEffect, useState } from 'react';
import ButtonAgain from '../components/ButtonAgain';
import api from '../api';
import _ from '../assets/utils'
import {connect} from 'react-redux'
import action from '../store/action'
/* 自定义表单校验规则 */
const validata = {
    phone(_, value) {
        value = value.trim();
        let reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/;
        if (value.length === 0) return Promise.reject(new Error('手机号是必填项！'))
        if (!reg.test(value)) return Promise.reject(new Error('手机号格式有误！'))
        return Promise.resolve();
    },
    code(_, value) {
        value = value.trim();
        let reg = /^\d{6}$/;
        if (value.length === 0) return Promise.reject(new Error('验证码是必填项！'))
        if (!reg.test(value)) return Promise.reject(new Error('验证码格式有误！'))
        return Promise.resolve();
    }
}
function Login(props) {
    let {queryUserInfoAsync,navigate,usp} = props;
    let [formIns] = Form.useForm(),
        [disabled, setDisabled] = useState(false),
        [sendText, setSendText] = useState('发送验证码')
    /* 表单提交 */
    const submit = async () => {
        try {
            await formIns.validateFields()
            let { phone, code } = formIns.getFieldValue();
            let { code: codeHttp, token } = await api.login(phone, code);
            if (+codeHttp !== 0) {
                Toast.show({
                    icon: 'fail',
                    content: '登录失败'
                })
                formIns.resetFields(['code'])
                return
            }
            //登录成功：存储Token、存储登录者信息到redux、提示、跳转
            _.storage.set('tk',token)
            await queryUserInfoAsync();//派发任务，同步redux中的状态信息
            Toast.show({
                icon:'success',
                content:'登录/注册成功'
            })
            let to = usp.get('to');
            to?navigate(to,{replace:true}):navigate(-1)
        } catch (_) { }
    }

    /* 发送验证码 */
    let timer = null,
        num = 31;
    let countTimer = () => {
        num--;
        if (num === 0) {
            clearInterval(timer)
            timer = null
            setSendText(`发送验证码`);
            setDisabled(false)
            return;
        }
        setSendText(`${num}秒后重发`)
    }
    const send = async () => {
        try {
            await formIns.validateFields(['phone'])
            //手机号格式验证通过
            let phone = formIns.getFieldValue('phone');
            let { code } = await api.sendPhoneCode(phone);
            if (+code !== 0) {
                Toast.show({
                    icon: 'fail',
                    content: '发送失败'
                })
                return
            }
            setDisabled(true)
            countTimer();
            if (!timer) timer = setInterval(countTimer, 1000)
        } catch (_) { console.log(_); }
    }
    /* 组件销毁的时候，把没有消除的定时器干掉 */
    useEffect(() => {
        return () => {
            if (timer) {
                clearInterval(timer);
                timer = null
            }
        }
    }, [])
    return <div className="login-box">
        <NavBarAgain title="登录和注册"></NavBarAgain>
        {/* layout='horizontal'  代表横向排列
        style={{ '--border-top': 'none' }} 去掉上边框
        */}
        <Form
            layout='horizontal'
            style={{ '--border-top': 'none' }}
            footer={
                <ButtonAgain onClick={submit} color='primary'>提交</ButtonAgain>}
            form={formIns}
            initialValues={{ phone: '', code: '' }} requiredMarkStyle='false'>
            <Form.Item name='phone' label='手机号' rules={[{ validator: validata.phone }]}>
                <Input placeholder="请输入手机号" />
            </Form.Item>
            {/* 在表单右侧加东西，比如按钮就用extra */}
            <Form.Item name='code' label='验证码'
                //  rules={[{validator:validata.code}]} 
                rules={[
                    { required: true, message: '验证码是必填项' },
                    { pattern: /^\d{6}$/, message: '验证码格式错误' }
                ]}
                extra={
                    <ButtonAgain size='small' color='primary'
                        onClick={send}
                        disabled={disabled} >
                        {sendText}
                    </ButtonAgain>
                }>
                <Input />
            </Form.Item>
        </Form>
    </div>
}
export default connect(null,action.base)(Login)